package com.mfp.java.testYou.core.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mfp.java.testYou.core.AppContext;
import com.mfp.java.testYou.core.UserSession;
import com.mfp.java.testYou.core.utils.UrlUtils;
import com.mfp.java.testYou.db.model.User;
import com.mfp.java.testYou.ui.mvc.LoginPage;

public class AuthenticationFilter implements Filter {

	private static final String[] BYPASS = new String[] { ".png", ".jpg", ".css", ".js" };

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpRequest = UrlUtils.wrapRequest(request);
		HttpServletResponse httpResponse = UrlUtils.wrapResponse(response);
		
		if (shouldBypass(httpRequest.getRequestURI())){
			chain.doFilter(request, response);
			return;
		}

		if (AppContext.isForceAuth()) {
			UserSession sess = AppContext.getUserSession(httpRequest);
			if (!sess.isLoggedIn()) {
				if (UrlUtils.redirectToTarget(httpRequest, httpResponse, LoginPage.URL)) {
					return;
				}
			}
		} else {
			UserSession sess = AppContext.getUserSession(httpRequest);
			if (!sess.isLoggedIn()) {
				httpRequest.getSession().setAttribute(UserSession.ATTRIBUTE_NAME, new UserSession(User.getJaneDo()));
			}
		}

		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

	private boolean shouldBypass(String uri) {
		String lowUri = uri.toLowerCase();
		for (String s : BYPASS){
			if (lowUri.endsWith(s)){
				return true;
			}
		}
		return false;
	}

}
